<?php

namespace app\admin\controller\product;

use app\common\controller\AdminBase;
use think\App;
use think\exception\ValidateException;

/**
 * Info控制器
 */
class Info extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\ProductInfo();

        $this->validate = \app\admin\validate\ProductInfo::class;
    }


    /**
     * 列表
     */
    public function index()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);
        $where = array();
        if (!empty($filters['category'])) {
            $where[] = array('a.category', '=', $filters['category']);
        }
        if (!empty($filters['product_type'])) {
            $where[] = array('a.flag', 'like', $filters['product_type']);
        }
        if (!empty($filters['brand'])) {
            $where[] = array('a.brand',  'like', '%' . $filters['brand'] . '%');
        }
        $list = $this->model
            ->where($where)
            // ->where('find_in_set(' . $filters['product_type'] . ',a.flag)')
            ->field('a.*,b.title,c.nickname')
            ->alias('a')
            ->join('qu_productcate b', 'a.category = b.id', 'left')
            ->join('system_admin c', 'a.dev_admin = c.id', 'left')
            ->order('a.sort desc')
            ->paginate($limit);
        $lists = $list->items();
        foreach ($lists as $k => $v) {
            $lists[$k]['xp_time'] = !empty($v['xp_time']) ? date('Y-m-d', $v['xp_time']) : 0;
            $lists[$k]['bp_time'] = !empty($v['bp_time']) ? date('Y-m-d', $v['bp_time']) : 0;
            $lists[$k]['dev_admin'] = !empty($v['nickname']) ?  $v['nickname'] : '';
            $lists[$k]['category'] = !empty($v['title']) ?  $v['title'] : '';
            $lists[$k]['product_type'] =  $v['product_type'] == 1 ?  '独立站' : 'tiktok';
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];
        return json($data);
    }

    public function edit()
    {
        $id = input('id');
        // halt($id);
        $row = $this->model->find($id);

        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if ($post['flag'] && is_array($post['flag'])) {
                $post['flag'] = implode(',', $post['flag']);
            }
            //禁止修改分类和编号
            unset($post['brand'], $post['category']);
            $post['xp_time'] =  !empty($post['xp_time']) ?  strtotime(date('Y-m-d', $post['xp_time']) . ' 00:00:00') : 0;
            $post['bp_time'] = !empty($post['bp_time']) ?  strtotime(date('Y-m-d', $post['bp_time']) . ' 00:00:00') : 0;
            $result = $row->save($post);
            if ($result) {
                return success('保存成功！');
            }
            return error('保存失败');
        }
        if ($row['flag']) {
            $arr = explode(",", $row['flag']);
            foreach ($arr as $k => $v) {
                $arr[$k] = $v * 1;
            }
            $row['flag'] = $arr;
        } else {
            $row['flag'] = [];
        }

        $row['bp_time'] = !empty($row['bp_time']) ? date('Y-m-d h:i:s', $row['bp_time']) : '';
        $row['xp_time'] = !empty($row['xp_time']) ? date('Y-m-d h:i:s', $row['xp_time']) : '';
        return success('ok', $row);
    }


    /**
     * 添加
     */
    public function add()
    {
        $post = $this->request->post();
        $categery = $post['category'];
        if (empty($categery)) {
            return error('请填写分类名称');
        }
        //查询条数生成sku编号
        $type_count = table('product_info')->where(['category' => $categery])->count();
        $type_count = $type_count + 1;
        $categery_title = table('productcate')->where(['id' => $categery])->find();
        $categery_title = !empty($categery_title['title']) ? $categery_title['title'] : '';
        if ($type_count > 10 || $type_count == 10) {
            $brand = $categery_title . $type_count;
        } else {
            $brand = $categery_title . '0' . $type_count;
        }
        //计算信息表的总条数,生成排序权重
        $sort_count = table('product_info')->count();
        $sort_count = $sort_count + 1;
        $post['brand'] = $brand;
        $post['sort'] = $sort_count;
        //查询当前类目下的总条数 自动生成sku编号和排序权重
        try {
            $this->validate && validate($this->validate)->check($post);
            $post['bp_time'] = !empty($post['bp_time']) ? strtotime(date('Y-m-d', $post['bp_time']) . ' 00:00:00') : '';
            $post['xp_time'] = !empty($post['xp_time']) ? strtotime(date('Y-m-d', $post['xp_time']) . ' 00:00:00') : '';;
            $result = $this->model->save($post);
            if ($result) {
                return success('添加成功！');
            }
            return error('添加失败');
        } catch (ValidateException $e) {
            return error($e->getError());
        } catch (\Exception $e) {
            return error('添加失败:' . $e->getMessage());
        }
    }

    //颜色罩杯管理器
    public function skumanage()
    {
        $id = input('id');
        //通过id查询对应的值
        $where[] = ['brand_id', '=', $id];
        $row = table('skumanager')->where($where)->select()->toarray();
        //回显
        $row = $this->processing_data($row);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (isset($post['color'])) {
                $where1[] = ['id', 'in', $post['color']];
                table('skumanager')->where($where)->where($where1)->update(['soft' => 1]);
            }
            if (isset($post['size'])) {
                $where2[] = ['id', 'in', $post['size']];
                table('skumanager')->where($where)->where($where2)->update(['soft' => 1]);
            }

            if (!empty($post['cup'])) {
                $where3[] = ['id', 'in', $post['cup']];
                table('skumanager')->where($where)->where($where3)->update(['soft' => 1]);
            }
            // 颜色,尺码,罩杯数据处理
            return success('操作成功');
        }
        $row['id'] = $id;
        return success('ok', $row);
    }

    //颜色罩杯管理器
    public function skumanageadd()
    {
        $id = input('id');
        //通过id查询对应的值
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $color = [];
            $size = [];
            $cup = [];
            // halt($post);
            if (!empty($post['color'][0])) {
                foreach ($post['color'] as  $v) {
                    if ($v['yingwen'] || $v['zhongwen']) {
                        $color[] = [
                            'brand_id' => $post['id'],
                            'title' => $v['yingwen'],
                            'ctitle' => $v['zhongwen'],
                            'type' => 1,
                        ];
                    }
                }
                if (!empty($color)) {
                    table('skumanager')->insertAll($color);
                }
            }
            if (!empty($post['size'][0])) {
                foreach ($post['size'] as  $v) {
                    if ($v['yingwen'] || $v['zhongwen']) {
                        $size[] = [
                            'brand_id' => $post['id'],
                            'title' => $v['yingwen'],
                            'ctitle' => $v['zhongwen'],
                            'type' => 2,
                        ];
                    }
                }
                if (!empty($size)) {
                    table('skumanager')->insertAll($size);
                }
            }

            if (!empty($post['cup'][0])) {
                foreach ($post['cup'] as  $v) {
                    if ($v['yingwen'] || $v['zhongwen']) {
                        $cup[] = [
                            'brand_id' => $post['id'],
                            'title' => $v['yingwen'],
                            'ctitle' => $v['zhongwen'],
                            'type' => 3,
                        ];
                    }
                }
                if (!empty($cup)) {
                    table('skumanager')->insertAll($cup);
                }
            }
            // 颜色,尺码,罩杯数据处理
            return success('操作成功');
        }
        $row = array();
        $row['id'] = $id;
        return success('ok', $row);
    }
    /**
     * 方法详情
     * @param array params
     */
    public function processing_data($skumanager)
    {
        $nums[1] = 1;
        $nums[2] = 2;
        $nums[3] = 3;
        $nums_soft[1] = 1;
        $nums_soft[2] = 2;
        $nums_soft[3] = 3;
        $row = array();
        if (!empty($skumanager)) {
            foreach ($skumanager as $k => $v) {
                switch ($v['type']) {
                    case '1':
                        $color = array();
                        $color['key'] = $v['id'];
                        $color['yingwen'] = $v['title'];
                        $color['zhongwen'] = $v['ctitle'];
                        $row['color'][] = $color;
                        if ($v['soft'] == 1) {
                            $row['color_soft'][] = $v['id'];
                        }
                        break;
                    case '2':
                        $cup = array();
                        $cup['key'] = $v['id'];
                        $cup['yingwen'] = $v['title'];
                        $cup['zhongwen'] = $v['ctitle'];
                        $row['cup'][] = $cup;
                        if ($v['soft'] == 1) {
                            $row['cup_soft'][] = $v['id'];
                        }
                        break;
                    case '3':
                        $size = array();
                        $size['key'] = $v['id'];
                        $size['yingwen'] = $v['title'];
                        $size['zhongwen'] = $v['ctitle'];
                        $row['size'][] = $size;
                        if ($v['soft'] == 1) {
                            $row['size_soft'][] = $v['id'];
                        }
                        break;
                    default:
                }
                if (isset($nums[$v['type']])) {
                    unset($nums[$v['type']]);
                }
                if (isset($nums_soft[$v['type']]) && $v['soft'] == 1) {
                    unset($nums_soft[$v['type']]);
                }
            }
        }
        if (!empty($nums)) {
            foreach ($nums as $k => $v) {
                switch ($v) {
                    case '1':
                        $row['color'] = [];
                        break;
                    case '2':
                        $row['cup'] = [];
                        break;
                    case '3':
                        $row['size'] = [];
                        break;
                    default:
                }
            }
        }
        if (!empty($nums_soft)) {
            foreach ($nums_soft as $k => $v) {
                switch ($v) {
                    case '1':
                        $row['color_soft'] = [];
                        break;
                    case '2':
                        $row['cup_soft'] = [];
                        break;
                    case '3':
                        $row['size_soft'] = [];
                        break;
                    default:
                }
            }
        }
        return $row;
    }
}
